package com.lemon.smartsafety.utils.common;

import android.text.Html;

import com.lemon.smartsafetynew.util.common.CommonUtil;
import com.lemon.smartsafetynew.util.constants.TimeFormatConstants;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串操作工具包
 *
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-3-21
 */
public class StringUtils {
    private final static Pattern emailer = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");

    private final static Pattern IMG_URL = Pattern.compile(".*?(gif|jpeg|png|jpg|bmp)");

    private final static Pattern URL = Pattern.compile("^(https|http)://.*?$(net|com|.com.cn|org|me|)");

    private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };

    public static boolean getBoolean(String string) {
        String boolString = StringUtils.nullValue(string);
        if (boolString.length() == 0) {
            return false;
        }
        if ("是".equals(boolString) || "1".equals(boolString) || "true".equalsIgnoreCase(boolString)) {
            return true;
        }
        return false;
    }



    /**
     * 判断是否为1
     * add Andrew.Yin 2017/8/23
     * @param status
     * @return
     */
    public static boolean getBoolean(Integer status) {
        return status != null && 1 == status;
    }

    /**
     * 将字符串转位日期类型
     *
     * @param sdate
     * @return
     */
    public static Date toDate(String sdate) {
        return toDate(sdate, dateFormater.get());
    }

    public static Date toDateYMD(String sdate) {
        return toDate(sdate, dateFormater2.get());
    }

    public static Date toDate(String sdate, SimpleDateFormat dateFormater) {
        try {
            return dateFormater.parse(sdate);
        } catch (ParseException e) {
            return null;
        }
    }

    public static String getDateString(Date date) {
        return dateFormater.get().format(date);
    }

    /**
     * 以友好的方式显示时间
     *
     * @param sdate
     * @return
     */
    public static String friendly_time(String sdate) {
        Date time = null;

        if (TimeZoneUtil.isInEasternEightZones()) time = toDate(sdate);
        else time = TimeZoneUtil.transformTime(toDate(sdate), TimeZone.getTimeZone("GMT+08"), TimeZone.getDefault());


        if (time == null) {
            time = DateUtils.getDateByFormat(sdate, DateUtils.dateFormatYMDHM);
        }

        if (time == null) {
            return "Unknown";
        }
        String   ftime = "";
        Calendar cal   = Calendar.getInstance();

        // 判断是否是同一天
        String curDate   = dateFormater2.get().format(cal.getTime());
        String paramDate = dateFormater2.get().format(time);
        if (curDate.equals(paramDate)) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0) ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前";
            else ftime = hour + "小时前";
            return ftime;
        }

        /* delete by Andrew.yin 2017/9/22 begin */
        /*
        long lt   = time.getTime() / 86400000;
        long ct   = cal.getTimeInMillis() / 86400000;
        int  days = (int) (ct - lt);
        if (days == 0) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0) ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前";
            else ftime = hour + "小时前";
        } else if (days == 1) {
            ftime = "昨天";
        } else if (days == 2) {
            ftime = "前天 ";
        } else if (days > 2 && days < 31) {
            ftime = days + "天前";
        } else if (days >= 31 && days <= 2 * 31) {
            ftime = "一个月前";
        } else if (days > 2 * 31 && days <= 3 * 31) {
            ftime = "2个月前";
        } else if (days > 3 * 31 && days <= 4 * 31) {
            ftime = "3个月前";
        } else {
            ftime = dateFormater2.get().format(time);
        }
        */
        /* delete by Andrew.yin 2017/9/22 end */

        long lt   = time.getTime() / 86400000;
        long ct   = cal.getTimeInMillis() / 86400000;
        int  days = (int) (ct - lt);
        if (days == 0) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0) ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前";
            else ftime = hour + "小时前";
        } else if (days == 1) {
            ftime = "昨天 " + CommonUtil.timeToStr(time, TimeFormatConstants.FORMAT_TIME2);
        } else if (days == 2) {
            ftime = "前天 " + CommonUtil.timeToStr(time, TimeFormatConstants.FORMAT_TIME2);
        } else {
            ftime = CommonUtil.timeToStr(time, TimeFormatConstants.FORMAT_TIME);
        }
        return ftime;
    }

    public static String friendly_time2(String sdate) {
        String res = "";
        if (isEmpty(sdate)) return "";

        String[] weekDays    = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        String   currentData = StringUtils.getDataTime("MM-dd");
        int      currentDay  = toInt(currentData.substring(3));
        int      currentMoth = toInt(currentData.substring(0, 2));

        int  sMoth = toInt(sdate.substring(5, 7));
        int  sDay  = toInt(sdate.substring(8, 10));
        int  sYear = toInt(sdate.substring(0, 4));
        Date dt    = new Date(sYear, sMoth - 1, sDay - 1);

        if (sDay == currentDay && sMoth == currentMoth) {
            res = "今天 / " + weekDays[getWeekOfDate(new Date())];
        } else if (sDay == currentDay + 1 && sMoth == currentMoth) {
            res = "昨天 / " + weekDays[(getWeekOfDate(new Date()) + 6) % 7];
        } else {
            if (sMoth < 10) {
                res = "0";
            }
            res += sMoth + "/";
            if (sDay < 10) {
                res += "0";
            }
            res += sDay + " / " + weekDays[getWeekOfDate(dt)];
        }

        return res;
    }

    /**
     * 获取当前日期是星期几<br>
     *
     * @param dt
     * @return 当前日期是星期几
     */
    public static int getWeekOfDate(Date dt) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) w = 0;
        return w;
    }

    /**
     * 判断给定字符串时间是否为今日
     *
     * @param sdate
     * @return boolean
     */
    public static boolean isToday(String sdate) {
        boolean b     = false;
        Date    time  = toDate(sdate);
        Date    today = new Date();
        if (time != null) {
            String nowDate  = dateFormater2.get().format(today);
            String timeDate = dateFormater2.get().format(time);
            if (nowDate.equals(timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 返回long类型的今天的日期
     *
     * @return
     */
    public static long getToday() {
        Calendar cal     = Calendar.getInstance();
        String   curDate = dateFormater2.get().format(cal.getTime());
        curDate = curDate.replace("-", "");
        return Long.parseLong(curDate);
    }

    public static String getCurTimeStr() {
        Calendar cal     = Calendar.getInstance();
        String   curDate = dateFormater.get().format(cal.getTime());
        return curDate;
    }

    /***
     * 计算两个时间差，返回的是的秒s
     *
     * @param dete1
     * @param date2
     * @return
     * @author 火蚁 2015-2-9 下午4:50:06
     */
    public static long calDateDifferent(String dete1, String date2) {

        long diff = 0;

        Date d1 = null;
        Date d2 = null;

        try {
            d1 = dateFormater.get().parse(dete1);
            d2 = dateFormater.get().parse(date2);

            // 毫秒ms
            diff = d2.getTime() - d1.getTime();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return diff / 1000;
    }

    /**
     * 判断给定字符串是否空白串。 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
     *
     * @param input
     * @return boolean
     */
    public static boolean isEmpty(String input) {
        if (input == null || "".equals(input)) return true;

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断给定字符串是否空白串 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
     * 只要有一个是空白就返回True
     */
    public static boolean isEmpty(String... strs) {
        for (String str : strs) {
            if (isEmpty(str)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 判断是不是一个合法的电子邮件地址
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        if (email == null || email.trim().length() == 0) return false;
        return emailer.matcher(email).matches();
    }

    /**
     * 判断一个url是否为图片url
     *
     * @param url
     * @return
     */
    public static boolean isImgUrl(String url) {
        if (url == null || url.trim().length() == 0) return false;
        return IMG_URL.matcher(url).matches();
    }

    /**
     * 判断是否为一个合法的url地址
     *
     * @param str
     * @return
     */
    public static boolean isUrl(String str) {
        if (str == null || str.trim().length() == 0) return false;
        return URL.matcher(str).matches();
    }

    /**
     * 字符串转整数
     *
     * @param str
     * @param defValue
     * @return
     */
    public static int toInt(String str, int defValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
        }
        return defValue;
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static int toInt(Object obj) {
        if (obj == null) return 0;
        return toInt(obj.toString(), 0);
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static long toLong(String obj) {
        try {
            return Long.parseLong(obj);
        } catch (Exception e) {
        }
        return 0;
    }

    /**
     * 字符串转布尔值
     *
     * @param b
     * @return 转换异常返回 false
     */
    public static boolean toBool(String b) {
        try {
            return Boolean.parseBoolean(b);
        } catch (Exception e) {
        }
        return false;
    }

    public static String nullValue(String oldString) {
        return isEmpty(oldString) ? "" : oldString;
    }

    public static String nullValue(String oldString, String defaultValue) {
        return isEmpty(oldString) ? defaultValue : oldString;
    }


    /**
     * 将一个InputStream流转换成字符串
     *
     * @param is
     * @return
     */
    public static String toConvertString(InputStream is) {
        StringBuffer      res  = new StringBuffer();
        InputStreamReader isr  = new InputStreamReader(is);
        BufferedReader    read = new BufferedReader(isr);
        try {
            String line;
            line = read.readLine();
            while (line != null) {
                res.append(line + "<br>");
                line = read.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != isr) {
                    isr.close();
                    isr.close();
                }
                if (null != read) {
                    read.close();
                    read = null;
                }
                if (null != is) {
                    is.close();
                    is = null;
                }
            } catch (IOException e) {
            }
        }
        return res.toString();
    }

    /***
     * 截取字符串
     *
     * @param start 从那里开始，0算起
     * @param num   截取多少个
     * @param str   截取的字符串
     * @return
     */
    public static String getSubString(int start, int num, String str) {
        if (str == null) {
            return "";
        }
        int leng = str.length();
        if (start < 0) {
            start = 0;
        }
        if (start > leng) {
            start = leng;
        }
        if (num < 0) {
            num = 1;
        }
        int end = start + num;
        if (end > leng) {
            end = leng;
        }
        return str.substring(start, end);
    }

    /**
     * 获取当前时间为每年第几周
     *
     * @return
     */
    public static int getWeekOfYear() {
        return getWeekOfYear(new Date());
    }

    /**
     * 获取当前时间为每年第几周
     *
     * @param date
     * @return
     */
    public static int getWeekOfYear(Date date) {
        Calendar c = Calendar.getInstance();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(date);
        int week = c.get(Calendar.WEEK_OF_YEAR) - 1;
        week = week == 0 ? 52 : week;
        return week > 0 ? week : 1;
    }

    public static int[] getCurrentDate() {
        int[]    dateBundle = new int[3];
        String[] temp       = getDataTime("yyyy-MM-dd").split("-");

        for (int i = 0; i < 3; i++) {
            try {
                dateBundle[i] = Integer.parseInt(temp[i]);
            } catch (Exception e) {
                dateBundle[i] = 0;
            }
        }
        return dateBundle;
    }

    /**
     * 返回当前系统时间
     */
    public static String getDataTime(String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.format(new Date());
    }


    /**
     * 将当前时间转换成指定的格式显示
     *
     * @param pattern 日期格式
     * @return 转换后的日期字符串
     */
    public static String dateToString(String pattern) {
        return getDateParser(pattern).format(new Date());
    }

    /**
     * 提供日期格式化工具
     *
     * @param pattern 日期格式
     * @return 格式化工具类
     */
    private static SimpleDateFormat getDateParser(String pattern) {
        return new SimpleDateFormat(pattern);
    }

    /**
     * 或得随机字符串
     *
     * @param length
     * @return String
     */
    public static String getRandomString(int length) {
        Random       random   = new Random();
        StringBuffer sbReturn = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(BASE_CHAR.length());
            sbReturn.append(BASE_CHAR.charAt(number));
        }
        return sbReturn.toString();
    }

    /**
     * 随机字符串源
     */
    private static final String BASE_CHAR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";


    /**
     * 描述：获取指定长度的字符所在位置.
     *
     * @param str  指定的字符串
     * @param maxL 要取到的长度（字符长度，中文字符计2个）
     * @return 字符的所在位置, 0代表没有
     */
    public static int subStringLength(String str, int maxL) {
        int    currentIndex = 0;
        int    valueLength  = 0;
        String chinese      = "[\u0391-\uFFE5]";
        //获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1
        for (int i = 0; i < str.length(); i++) {
            //获取一个字符
            String temp = str.substring(i, i + 1);
            //判断是否为中文字符
            if (temp.matches(chinese)) {
                //中文字符长度为2
                valueLength += 2;
            } else {
                //其他字符长度为1
                valueLength += 1;
            }
            if (valueLength >= maxL) {
                currentIndex = i;
                break;
            }
        }
        return currentIndex;
    }

    // Hex help
    private final static byte[] HEX_CHAR_TABLE = {(byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F'};

    public static String getHexString(byte[] raw) {
        return getHexString(raw, raw.length);
    }

    /**
     * convert a byte arrary to hex string
     *
     * @param raw byte arrary
     * @param len lenght of the arrary.
     * @return hex string.
     */
    public static String getHexString(byte[] raw, int len) {
        if (raw == null || len == 0) {
            return "";
        }
        byte[] hex   = new byte[2 * len];
        int    index = 0;
        int    pos   = 0;

        for (byte b : raw) {
            if (pos >= len) break;

            pos++;
            int v = b & 0xFF;
            hex[index++] = HEX_CHAR_TABLE[v >>> 4];
            hex[index++] = HEX_CHAR_TABLE[v & 0xF];
        }

        return new String(hex);
    }

    /**
     * 将List用分割符号分割
     *
     * @param strings
     * @param split
     * @return
     */
    public static String getStringWithSplit(List<String> strings, String split) {
        StringBuilder builder = new StringBuilder();
        for (int j = 0; j < strings.size(); j++) {
            if (j != 0) {
                builder.append(split + strings.get(j));
            } else {
                builder.append(strings.get(j));
            }
        }
        return builder.toString();
    }


    public static boolean orEquals(String comp1, String... strs) {
        for (String str : strs) {
            if (comp1.equals(str)) {
                return true;
            }
        }
        return false;
    }

    public static String encoding(String src) {
        if (src == null) return "";
        StringBuilder result = new StringBuilder();
        if (src != null) {
            src = src.trim();
            for (int pos = 0; pos < src.length(); pos++) {
                switch (src.charAt(pos)) {
                    case '\"':
                        result.append("&quot;");
                        break;
                    case '<':
                        result.append("&lt;");
                        break;
                    case '>':
                        result.append("&gt;");
                        break;
                    case '\'':
                        result.append("&apos;");
                        break;
                    case '%':
                        result.append("&pc;");
                        break;
                    case '_':
                        result.append("&ul;");
                        break;
                    case '#':
                        result.append("&shap;");
                        break;
                    case '?':
                        result.append("&ques;");
                        break;
                    case '&':
                        result.append("&amp;");
                        break;
                    default:
                        result.append(src.charAt(pos));
                        break;
                }
            }
        }
        return result.toString();
    }


    public static String htmlDecode(String str) {
        if (str == null) {
            return "";
        } else {
            String s = StringUtils.replace(str, "&lt;", "<");
            s = StringUtils.replace(s, "&gt;", ">");
            s = StringUtils.replace(s, "&nbsp;", " ");
            s = StringUtils.replace(s, "&quot;", "\"");
            s = StringUtils.replace(s, "&apos;", "\'");
            s = StringUtils.replace(s, "&pc;", "%");
            s = StringUtils.replace(s, "&ul;", "_");
            s = StringUtils.replace(s, "&shap;", "#");
            s = StringUtils.replace(s, "&ques;", "?");
            s = StringUtils.replace(s, "&amp;", "&");

            return s;
        }
    }


    /**
     * 替换子字符串，例如：将ABCDEFGAB中的AB替换成12之后，返回12CDEFG12。
     *
     * @param str        父字符串
     * @param sPattern   欲替换的内容
     * @param sReplaceBy 替换后的内容
     * @return 替换后的串
     */
    public final static String replace(String str, String sPattern, String sReplaceBy) {
        if (str == null) {
            return "";
        }
        int          s      = 0;
        int          e      = 0;
        StringBuffer bufRet = new StringBuffer();
        while ((e = str.indexOf(sPattern, s)) >= 0) {
            bufRet.append(str.substring(s, e));
            bufRet.append(sReplaceBy);
            s = e + sPattern.length();
        }
        bufRet.append(str.substring(s));
        return bufRet.toString();
    }


    public enum ColorStatus {
        STATUS_RED("#ff5722"), STATUS_YELLOW("#FE9600"), STATUS_GREEN("#4CAF50"), STATUS_BLUE("#03A9F4"), STATUS_GRAY("#B6B6B6"),STATUS_COMMON("#000000"),;
        private String colorString;

        public String getColorString() {
            return colorString;
        }

        public void setColorString(String colorString) {
            this.colorString = colorString;
        }

        private ColorStatus(String colorString) {
            this.colorString = colorString;
        }

    }

    public static CharSequence getStatusString(String string, ColorStatus status) {
        return Html.fromHtml("<font color=" + status.getColorString() + ">" + string + "</font>");
    }


    /**
     * 获取字符串中文字符的长度（每个中文算2个字符）.
     *
     * @param str 指定的字符串
     * @return 中文字符的长度
     */
    public static int chineseLength(String str) {
        int    valueLength = 0;
        String chinese     = "[\u0391-\uFFE5]";
        /* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
        if (!isEmpty(str)) {
            for (int i = 0; i < str.length(); i++) {
                /* 获取一个字符 */
                String temp = str.substring(i, i + 1);
	            /* 判断是否为中文字符 */
                if (temp.matches(chinese)) {
                    valueLength += 2;
                }
            }
        }
        return valueLength;
    }


    /**
     * 获取Set的逗号分个字符串
     * @param set
     * @return
     */
    public static String getSetString(Set<String> set) {
        if (null == set || set.isEmpty()) {
            return "";
        }
        return replaceBlank(set.toString().replace("[", "").replace("]", ""));
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }


}
